package com.menggudf.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.menggudf.dao.*;
import com.menggudf.entity.*;
import com.menggudf.model.InvitationModel;
import com.menggudf.service.InvitationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.menggudf.commom.CommonUtils;
import com.menggudf.common.utils.DateUtils;
import com.menggudf.model.BMIrecordModel;
import com.menggudf.model.ResultModel;
import com.menggudf.model.UserModel;
import com.menggudf.service.UserService;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger LOGGER = LoggerFactory
            .getLogger(UserServiceImpl.class);
    
    @Autowired
    private UserDao userDao;
    
    @Autowired
    MembersDao membersDao;
    
    @Autowired
    BMIrecordDao bMIrecordDao;

    @Autowired
    InvitationDao invitationDao;

    @Autowired
    InvitationUseRecordDao invitationUseRecordDao;
    
    @Override
    @Transactional(value = "medicalTM", rollbackFor = Exception.class)
    public void insert(String string, int i) {
        User t=new User();
        t.setUserName("则");
        t.setPassword("123123");
        userDao.persist(t);
        System.out.println("1231 ");
        
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor = Exception.class)
    public ResultModel userRegister(UserModel user,String invitationCode) {

        //校验邀请码
        Invitation i = invitationDao.findByInvitationCode(invitationCode);
        if(i == null){
            return ResultModel.fail("注册失败，邀请码错误", null);
        }

        //查询记录

        User u = (User) userDao.findByPhone(user.getPhone());
        if(u!=null){
            return ResultModel.fail("用户已存在，请登录",null);
        }
        User us = new User();
        String uuid = UUID.randomUUID().toString();
        us.setUserCode(uuid);
        us.setUserName(user.getUserName());
        if(StringUtils.isEmpty(user.getPassword())){
            return ResultModel.fail("密码不能为空",null);
        }
        us.setPassword(CommonUtils.GetMD5Code(user.getPassword()));
        if(StringUtils.isEmpty(user.getPhone())){
            return ResultModel.fail("手机号或邮箱不能为空",null);
        }
        us.setPhone(user.getPhone());
        if(user.getBirth()!=null){
            us.setBirth(user.getBirth());
        }
        if(user.getSex()!=null){
            us.setSex(user.getSex());
        }
        Date date = new Date();
        us.setCreateTime(date);
        us.setIsRead(user.getIsRead());

        InvitationUseRecord iur = new InvitationUseRecord();
        iur.setCreateTime(date);
        iur.setInvitationCode(invitationCode);
        iur.setUserCode(uuid);
        iur.setUserName(us.getUserName());
        try {
            userDao.persist(us);

            if(i.getIsUsed()==0){
                //设置邀请码状态
                i.setIsUsed(1);
                /*i.setUserName(us.getUserName());
                i.setUserCode(us.getUserCode());*/
                invitationDao.merge(i);
            }

            //添加邀请码记录
            invitationUseRecordDao.persist(iur);
            return ResultModel.success("注册成功", null);
        } catch (Exception e) {
            LOGGER.error("注册失败",e);
        }
        
        return ResultModel.fail("注册失败", null);
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public ResultModel userLogin(String phone,String passWord) {
        User u = userDao.findByPhone(phone);
        if(u==null){
            return ResultModel.fail();
        }
/*        System.out.println(passWord);
        System.out.println(CommonUtils.GetMD5Code(passWord));
        System.out.println(u.getPassword());
        System.out.println(!CommonUtils.GetMD5Code(passWord).equals(u.getPassword()));*/
        if(!CommonUtils.GetMD5Code(passWord).equals(u.getPassword())){
            return ResultModel.fail("密码不对", null);
        }
        UserModel um = new UserModel();
        um.setBirth(u.getBirth());
        um.setDay(DateUtils.dateGap(new Date(), u.getBirth()));
        um.setSex(u.getSex());
        um.setUserCode(u.getUserCode());
        um.setPhone(u.getPhone());
        um.setUserName(u.getUserName());
        um.setRealName(u.getRealName());
        return ResultModel.success("登录成功", um);
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public Map<String, Object> getUserList(
            String userCode,
            String userName,
            int pageSize,
            int offset,
            Date startTime,
            Date endTime) {
        List<User> list = userDao.getUserList(userCode,userName,pageSize,offset,startTime, endTime);
        long count = userDao.getUserListCount(userCode, userName, startTime, endTime);
        List<UserModel> mlist = new ArrayList<UserModel>();
        for(User u :list){
            UserModel um = new UserModel();
            um.setBirth(u.getBirth());
            //um.setDay(DateUtils.dateGap(new Date(), u.getBirth()));
            um.setCreateTime(u.getCreateTime());
            um.setPhone(u.getPhone());
            um.setRealName(u.getRealName());
            um.setSex(u.getSex());
            um.setUserCode(u.getUserCode());
            um.setUserName(u.getUserName());
            mlist.add(um);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", count);
        map.put("rows", mlist);
        return map;
    }

    @Override
    @Transactional(value = "medicalTM", readOnly = true)
    public ResultModel getRoles(String primaryRole) {
        //查询主用户信息
        User u = userDao.findByUserCode(primaryRole);
        if(u==null){
            return ResultModel.fail("当前用户不存在", null);
        }
        //查询主用户的子角色
        List<Members> list = membersDao.getMembersByUserCode(u.getUserCode());
        List<UserModel> uList = new ArrayList<UserModel>();
        //插入主用户信息
        UserModel umodel = new UserModel();
        umodel.setBirth(u.getBirth());
        umodel.setDay(DateUtils.dateGap(new Date(), u.getBirth()));
        umodel.setCreateTime(u.getCreateTime());
        umodel.setPhone(u.getPhone());
        umodel.setRealName(u.getRealName());
        umodel.setSex(u.getSex());
        umodel.setUserCode(u.getUserCode());
        umodel.setUserName(u.getUserName());
        umodel.setIsMainRole(1);//设置为主账号
        uList.add(umodel);
        //循环插入子角色信息
        for(Members m : list){
            UserModel um = new UserModel();
            um.setUserCode(m.getRoleCode());
            um.setUserName(m.getRoleName());
            um.setBirth(m.getBirth());
            um.setDay(DateUtils.dateGap(new Date(), m.getBirth()));
            um.setSex(m.getSex());
            um.setIsMainRole(0);//设置为主账号
            uList.add(um);
        }
        return ResultModel.success("获取成功", uList);
    }

    @Override
    @Transactional(value = "medicalTM", readOnly = true)
    public ResultModel currRole(String currRole, Integer isMainRole) {
        UserModel umodel = new UserModel();
        if(isMainRole==1){
            User u = userDao.findByUserCode(currRole);
            if(u==null){
                return ResultModel.fail("角色不存在", null);
            }
            umodel.setBirth(u.getBirth());
            umodel.setDay(DateUtils.dateGap(new Date(), u.getBirth()));
            umodel.setPhone(u.getPhone());
            umodel.setRealName(u.getRealName());
            umodel.setSex(u.getSex());
            umodel.setUserCode(u.getUserCode());
            umodel.setUserName(u.getUserName());
            umodel.setIsMainRole(1);//设置为主账号
        }else if(isMainRole==0){
            Members m = membersDao.getMembersByRoleCode(currRole);
            if(m==null){
                return ResultModel.fail("角色不存在", null);
            }
            umodel.setUserCode(m.getRoleCode());
            umodel.setUserName(m.getRoleName());
            umodel.setBirth(m.getBirth());
            umodel.setDay(DateUtils.dateGap(new Date(), m.getBirth()));
            umodel.setSex(m.getSex());
            umodel.setIsMainRole(0);//设置为主账号
        }else{
            return ResultModel.fail("参数错误", null);
        }
        return ResultModel.success("获取成功", umodel);
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel editUser(
            String currRole,
            Integer isMainRole,
            String name,
            Integer sex,
            Date birth) {
        if(isMainRole==1){
            User u = userDao.findByUserCode(currRole);
            if(u==null){
                return ResultModel.fail("用户不存在", null);
            }
            try {
                u.setBirth(birth);
                if(!StringUtils.isEmpty(name)){
                    u.setRealName(name);
                }
                u.setSex(sex);
                userDao.merge(u);
                return ResultModel.success();
            } catch (Exception e) {
                LOGGER.error("editUser fail",e);
            }
            return ResultModel.fail();
        }else{
            Members m = membersDao.getMembersByRoleCode(currRole);
            if(m==null){
                return ResultModel.fail("角色不存在", null);
            }
            m.setBirth(birth);
            m.setSex(sex);
            if(!StringUtils.isEmpty(name)){
                m.setRoleName(name);
            }
            try {
                membersDao.merge(m);
                return ResultModel.success();
            } catch (Exception e) {
                LOGGER.error("editUser fail",e);
            }
            return ResultModel.fail();
        }

    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel findUserPsw(String phone, String password) {
        User u = userDao.findByPhone(phone);
        if(u==null){
            return ResultModel.fail();
        }
        try {
            u.setPassword(CommonUtils.GetMD5Code(password));
            userDao.merge(u);
            return ResultModel.success();
        } catch (Exception e) {
            LOGGER.error("findUserPsw fail",e);
        }
        return ResultModel.fail();
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel createRole(String name, Integer sex, Date birth,String userCode) {
        try {
            Members m = new Members();
            m.setBirth(birth);
            m.setUserCode(userCode);
            m.setRoleName(name);
            m.setSex(sex);
            m.setRoleCode(UUID.randomUUID().toString());
            membersDao.persist(m);
            return ResultModel.success("创建成功",null);
        } catch (Exception e) {
            LOGGER.error("createRole fail",e);
        }

        return ResultModel.fail("创建失败", null);
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public UserModel getUserDetail(String userCode) {
        User u = userDao.getUserDetail(userCode);
        UserModel um = new UserModel();
        if(u!=null){
            um.setBirth(u.getBirth());
            um.setDay(DateUtils.dateGap(new Date(), u.getBirth()));
            um.setCreateTime(u.getCreateTime());
            um.setPhone(u.getPhone());
            um.setRealName(u.getRealName());
            um.setSex(u.getSex());
            um.setUserCode(u.getUserCode());
            um.setUserName(u.getUserName());
        }
        return um;
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel addBMIRecord(
            String userCode,
            String roleCode,
            Double bodyWeight,
            Double height) {
        BMIrecord bmi = new BMIrecord();
        bmi.setBodyWeight(bodyWeight);
        bmi.setHeight(height);
        bmi.setRoleCode(roleCode);
        bmi.setUserCode(userCode);
        bmi.setCreatedTime(new Date());
        try {
            bMIrecordDao.persist(bmi);
            return ResultModel.success("添加成功", null);
        } catch (Exception e) {
            LOGGER.error("addBMIRecord fail",e);
        }
        return ResultModel.fail("添加失败", null);
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public ResultModel getBMIRecord(String userCode, String roleCode) {
        BMIrecord bmi = bMIrecordDao.getBMIRecordLastOne(userCode,roleCode);
        BMIrecordModel bmiModel = new BMIrecordModel();
        if(bmi!=null){
            bmiModel.setBodyWeight(bmi.getBodyWeight());
            bmiModel.setCreatedTime(bmi.getCreatedTime());
            bmiModel.setHeight(bmi.getHeight());
            bmiModel.setId(bmi.getId());
            bmiModel.setRoleCode(bmi.getUserCode());
            bmiModel.setUserCode(bmi.getUserCode());
        }
        return ResultModel.success("获取成功", bmiModel);
    }
}
